package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.utils.R;
import io.renren.modules.erp.entity.MaterialCategory;
import io.renren.modules.erp.service.MaterialCategoryService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.erp.vo.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ji—sheng—hua   jshERP
 */
@RestController
@RequestMapping(value = "/materialCategory")
public class MaterialCategoryController  extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(MaterialCategoryController.class);

    @Resource
    private MaterialCategoryService materialCategoryService;

    @GetMapping(value = "/getAllList")
    public R getAllList(@RequestParam("parentId") Long parentId, HttpServletRequest request) throws Exception{
        List<MaterialCategory> materialCategoryList = materialCategoryService.getAllList(parentId);
        return R.ok().put("data",materialCategoryList);
    }

    /**
     * 根据id来查询商品名称
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/findById")
    public R findById(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        List<MaterialCategory> dataList = materialCategoryService.findById(id);
        JSONObject outer = new JSONObject();
        if (null != dataList) {
            for (MaterialCategory mc : dataList) {
                outer.put("id", mc.getId());
                outer.put("name", mc.getName());
                outer.put("parentId", mc.getParentId());
                List<MaterialCategory> dataParentList = materialCategoryService.findById(mc.getParentId());
                if(dataParentList!=null&&dataParentList.size()>0){
                    outer.put("parentName", dataParentList.get(0).getName());
                }
                outer.put("sort", mc.getSort());
                outer.put("serialNo", mc.getSerialNo());
                outer.put("remark", mc.getRemark());
            }
        }
        return R.ok().put("data",outer);
    }
    /**
     * create by: cjl
     * description:
     * 获取商品类别树数据
     * create time: 2019/2/19 11:49
     * @Param:
     * @return com.alibaba.fastjson.JSONArray
     */
    @RequestMapping(value = "/getMaterialCategoryTree")
    public R getMaterialCategoryTree(@RequestParam("id") Long id) throws Exception{
        JSONArray arr=new JSONArray();
        List<TreeNode> materialCategoryTree = materialCategoryService.getMaterialCategoryTree(id);
        if(materialCategoryTree!=null&&materialCategoryTree.size()>0){
            for(TreeNode node:materialCategoryTree){
                String str=JSON.toJSONString(node);
                JSONObject obj=JSON.parseObject(str);
                arr.add(obj) ;
            }
        }
        return R.ok().put("data",arr);
    }
    /**
     * create by: cjl
     * description:
     *  新增商品类别数据
     * create time: 2019/2/19 17:17
     * @Param: beanJson
     * @return java.lang.Object
     */
    @RequestMapping(value = "/addMaterialCategory")
    public Object addMaterialCategory(@RequestBody MaterialCategory mc) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        int i= materialCategoryService.addMaterialCategory(mc,getUserId());
        if(i<1){
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_ADD_FAILED_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_ADD_FAILED_MSG);
        }
        return result;
    }
    /**
     * create by: cjl
     * description:
     *  修改商品类别数据
     * create time: 2019/2/20 9:30
     * @Param: beanJson
     * @return java.lang.Object
     */
    @RequestMapping(value = "/editMaterialCategory")
    public Object editMaterialCategory(@RequestBody MaterialCategory mc) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
//        MaterialCategory mc= JSON.parseObject(beanJson, MaterialCategory.class);
        int i= materialCategoryService.editMaterialCategory(mc,getUserId());
        if(i<1){
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_EDIT_FAILED_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_EDIT_FAILED_MSG);
        }
        return result;
    }
    /**
     * create by: cjl
     * description:
     *  批量删除商品类别信息
     * create time: 2019/2/19 17:26
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteMaterialCategory")
    public Object batchDeleteMaterialCategory(@RequestParam("ids") String ids,@RequestParam(value="deleteType",
            required =false,defaultValue= BusinessConstants.DELETE_TYPE_NORMAL)String deleteType) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        int i=0;
        if(BusinessConstants.DELETE_TYPE_NORMAL.equals(deleteType)){
            i= materialCategoryService.batchDeleteMaterialCategoryByIdsNormal(ids,getUserId());
        }else if(BusinessConstants.DELETE_TYPE_FORCE.equals(deleteType)){
            i= materialCategoryService.batchDeleteMaterialCategoryByIds(ids,getUserId());
        }else{
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}],deleteType[{}]",
                    ExceptionConstants.DELETE_REFUSED_CODE,ExceptionConstants.DELETE_REFUSED_MSG,ids,deleteType);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_REFUSED_CODE,
                    ExceptionConstants.DELETE_REFUSED_MSG);
        }
        if(i<1){
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_DELETE_FAILED_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_DELETE_FAILED_MSG);
        }
        return result;
    }

    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request)throws Exception {
        if(1==materialCategoryService.insertMaterialCategory(beanJson, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    public R update(@RequestBody String beanJson,@RequestParam("id")Long id, HttpServletRequest request)throws Exception {
        if(1==materialCategoryService.updateMaterialCategory(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id")Long id, HttpServletRequest request)throws Exception {
        if(1==materialCategoryService.deleteMaterialCategory(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids") String ids, HttpServletRequest request)throws Exception {
        if(1==materialCategoryService.batchDeleteMaterialCategory(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<materialCategoryService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }
}
